package com.etl.task.order;

import com.etl.constant.ResultField;
import com.etl.extract.QueryParameter;
import com.etl.extract.ScheduleTask;
import com.etl.task.basic.AbstractTask;
import com.etl.task.basic.TaskResult;
import com.etl.task.handler.FilmTicketHandler;
import com.etl.task.handler.GoodsHandler;
import com.etl.task.handler.OrderHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 退货订单任务
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-10-14 17:17
 */
@Slf4j
@Service("RejectOrderTask")
public class RejectOrderTask extends AbstractTask {

    @Autowired
    OrderHandler orderHandler;

    @Autowired
    GoodsHandler goodsHandler;

    @Autowired
    FilmTicketHandler filmTicketHandler;

    /**
     * 执行任务抽象方法
     *
     * @param scheduleTask 调度任务
     */
    @Override
    public TaskResult executeTask(ScheduleTask scheduleTask) {
        QueryParameter queryParameter = QueryParameter.of(scheduleTask);
        List<Map<String, String>> orderList = orderHandler.findRejectBillList(
                scheduleTask, queryParameter.getParameterMap());
        if (CollectionUtils.isEmpty(orderList)) {
            return TaskResult.builder()
                    .code(TaskResult.SUCCESS_CODE)
                    .lastSign(scheduleTask.getSchedule().getLastSign())
                    .build();
        }
        // 组装订单编码参数
        List<String> billCodeList = orderList.parallelStream()
                .map(map -> map.get(ResultField.BILL_CODE)).collect(Collectors.toList());
        queryParameter.put("billCodeList", billCodeList);
        // 查询销售商品列表
        List<Map<String, String>> goodsList = goodsHandler.findRejectGoodsList(
                scheduleTask, queryParameter.getParameterMap());
        // 查询销售放映计划列表
        List<Map<String, String>> planList = filmTicketHandler.findRejectPlanList(
                scheduleTask, queryParameter.getParameterMap());
        // 保存ES订单文档列表
        orderHandler.saveOrderDocumentList(scheduleTask, orderList, goodsList, planList);
        return TaskResult.builder()
                .code(TaskResult.SUCCESS_CODE)
                .handlerNum(orderList.size())
                .lastSign(orderList.get(orderList.size() - 1).get(ResultField.PAYED_TIME))
                .build();
    }
}
